package com.heima.search.service.impl;

import com.heima.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//搜索记录,用户线程池异步保存记录
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 插入用户搜索记录并保存
     * @param dto
     */

    //异步注解(线程池名称)
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDto dto) {
        //1.查询dto参数(search word不能为空)
        if(StringUtils.isBlank(dto.getSearchWords())){
         throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"搜索关键词不能为空");
        }
        //2.查询行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(), dto.getEquipmentId());
        if(apBehaviorEntry==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"查询实体不存在");
        }
        //3.查询当前用户 搜索的关键词 在 搜索记录中 是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(
                Query.query(
                Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("keyword").is(dto.getSearchWords()))
                ,ApUserSearch.class);

        //4.如果存在,更新时间并保存
        if(apUserSearch!=null){
         apUserSearch.setCreatedTime(new Date());
         mongoTemplate.save(apUserSearch);
        }else {
            //5.如果不存在,保存信息并保存
        apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        // 查询当前用户的行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry =
                behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(),userSearchDto.getEquipmentId());
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到关联的行为实体数据");
        }
        // 按照时间倒序,查询前十条数据
        Query query = Query.query(Criteria
                .where("entryId").is(apBehaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto historyDto) {
        //查询当前用户的行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user == null?null:user.getId(),historyDto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到相关联的实体数据2");
        }
        //查询出需要删除的字段信息
        Query query1 = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("id").is(historyDto.getId()));
        mongoTemplate.remove(query1,ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
